package com.controls.ws;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.content.Context;

import com.Utility.WebServiceCommunicator.WebServiceFlag;
import com.events.WebServiceCommunicatorListener;
import com.objects.CountrySMSCode;
import com.objects.OutboxObject;

public class OutboxWSControl extends BaseWSControl {
	public OutboxWSControl(Context cxt, WebServiceCommunicatorListener lsn) {
		super(cxt, lsn);
	}

	public boolean GetUserOutbox(String accessToken, String month, String year) {
		String content = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
				+ "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
				+ "<soap:Body>"
				+ "<GetUserOutbox xmlns=\"https://www.privacydatasolutions.net/\">"
				+ "<Token>" + accessToken + "</Token>" + "<Month>" + month
				+ "</Month>" + "<Year>" + year + "</Year>" + "</GetUserOutbox>"
				+ "</soap:Body>" + "</soap:Envelope>";

		fetch(WebServiceFlag.GET_OUTBOX, content);
		return true;
	}

	public ArrayList<OutboxObject> parseOutbox(String xml) {
		ArrayList<OutboxObject> items = new ArrayList<OutboxObject>();
		Document doc = getDomElement(xml);
		if (doc == null) {
			return items;
		}

		NodeList results = doc.getElementsByTagName("GetUserOutboxResult");
		JSONArray mArray = null;
		if (results.getLength() > 0) {
			Node node = results.item(0);
			try {
				mArray = new JSONArray(node.getTextContent());
			} catch (DOMException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (mArray != null) {
			for (int i = 0; i < mArray.length(); i++) {
				try {
					JSONObject obj = mArray.getJSONObject(i);
					OutboxObject item = new OutboxObject();
					if (obj.has("Attachments")) {
						item.setAttach(obj.getString("Attachments"));
					}
					if (obj.has("DateTime")) {
						item.setDateTime(obj.getString("DateTime"));
					}
					if (obj.has("Description")) {
						item.setDescription(obj.getString("Description"));
					}
					if (obj.has("MsgGUID")) {
						item.setMsgGUID(obj.getString("MsgGUID"));
					}
					if (obj.has("Recipient")) {
						item.setRecippient(obj.getString("Recipient"));
					}
					if (obj.has("Status")) {
						item.setStatus(obj.getString("Status"));
					}
					if (obj.has("UniqueGUID")) {
						item.setUniqueGUID(obj.getString("UniqueGUID"));
					}

					items.add(item);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}
		return items;
	}
}
